const Koa = require('koa')
const koaBody = require('koa-body')
const koaRouter = require('koa-router')
const koaStaticCache = require('koa-static-cache')
const nunjucks = require('nunjucks')
const fs = require('fs')
const mysql = require('mysql2/promise')

async function run() {
    const connection = await mysql.createConnection({
        host: 'localhost',
        user: 'root',
        database: 'kkb-mall',
        password: 'sxzpapa11'
    })
    
    const server = new Koa()
    
    server.use(koaStaticCache({
        prefix: '/public',
        dir: './public',
        gzip: true,
        dynamic: true
    }))
    
    const router = new koaRouter()
    
    router.get('/index',async (ctx,next)=>{
        const [items] = await connection.query('SELECT * FROM items')
        const tpl = fs.readFileSync('./public/template/index.html').toString()
        ctx.body = nunjucks.renderString(tpl, {
            items
        })
    })
    
    server.use(router.routes())
    
    server.listen(8080)
}
run()